R 基本指令(AI ver)

R 語言 Base 指令整理(不使用 package)

1. 環境與工作空間

清除變數

rm(list = ls())

查看目前所有變數

ls()

查看變數內容

print(x)

查看物件結構

str(x)

查看物件摘要

summary(x)

查看物件型態

class(x)
typeof(x)

查看物件長度

length(x)

2. 基本資料型態

R 主要型態:

numeric
integer
character
logical
factor

範例

x <- 10
y <- "hello"
z <- TRUE

3. 向量操作

建立向量

c(1,2,3,4)

建立連續數列

1:10

seq(1,10,by=2)

重複數值

rep(1,5)

rep(c(1,2),3)

4. 基本數學運算

+   # 加
-   # 減
*   # 乘
/   # 除
^   # 次方
%%  # 取餘數
%/% # 整數除法

範例

5^2
10 %% 3
10 %/% 3

5. 常用數學函數

sum(x)
mean(x)
median(x)
min(x)
max(x)
range(x)
sd(x)
var(x)

6. 邏輯運算

==   # 等於
!=   # 不等於
>    # 大於
<    # 小於
>=
<=

邏輯運算

&   # and
|   # or
!   # not

範例

x > 5
x == 10

7. 條件判斷

if

if(x > 0){
  print("positive")
}

if else

if(x > 0){
  print("positive")
}else{
  print("negative")
}

ifelse (向量化)

ifelse(x > 5, "big", "small")

8. 迴圈

for

for(i in 1:5){
  print(i)
}

while

i <- 1
while(i <= 5){
  print(i)
  i <- i + 1
}

repeat

repeat{
  print("hello")
  break
}

9. 字串處理

合併字串

paste("A",1)

指定分隔符

paste("A",1,sep="")

不加空格

paste0("A",1)

字串長度

nchar("hello")

字串分割

strsplit("A,B,C",",")

10. 向量篩選

x <- c(1,3,5,7,9)

x[x > 5]

結果

7 9

11. NA 處理

判斷 NA

is.na(x)

移除 NA

na.omit(x)

12. matrix 操作

建立 matrix

matrix(1:9, nrow=3)

指定 row / column

matrix(1:9, nrow=3, byrow=TRUE)

取元素

m[1,2]

取整列

m[1,]

取整欄

m[,2]

13. data.frame

建立 data frame

df <- data.frame(
  name = c("A","B"),
  age = c(20,25)
)

查看資料

head(df)
tail(df)

取欄位

df$name

df[,1]

14. apply 家族

apply(matrix)

apply(m, 1, sum)
1 = row
2 = column

lapply

lapply(list(1:3,4:6), sum)

sapply

sapply(1:10, sqrt)

tapply

tapply(x, group, mean)

15. 排序

sort(x)

反向排序

sort(x, decreasing=TRUE)

取得排序 index

order(x)

16. 抽樣

sample(1:10,5)

不重複抽樣

sample(1:10,5,replace=FALSE)

17. 隨機數

runif(10)

常態分布

rnorm(10)

18. 分布函數(統計)

R 分布函數有固定規則:

類型 功能
r random
d density
p cdf
q quantile

例如:

常態分布

rnorm(10, mean = 0, sd = 1)
dnorm(0)
pnorm(1.96)
qnorm(0.975)

二項分布

rbinom(10, size=10, prob=0.5)

poisson

rpois(10, lambda=3)

19. 讀寫資料

讀取 CSV

read.csv("file.csv")

寫入 CSV

write.csv(df,"file.csv")

20. 顯示設定

關閉科學記號

options(scipen=999)

設定小數位

options(digits=4)

21. 自訂函數

my_function <- function(x){

  result <- sum(x)

  return(result)

}

22. package 檢查(你整理的)

"readxl" %in% rownames(installed.packages())

5 個「超常用但很多人漏掉」

  1. 查看資料維度
dim(df)
  1. 查看欄位名稱
names(df)
colnames(df)
  1. 轉型
as.numeric(x)
as.character(x)
as.factor(x)
  1. unique
unique(x)
  1. table
table(x)

矩陣與數值計算(演算法常用)


1 建立矩陣

# 建立矩陣
A <- matrix(1:9, nrow=3, ncol=3)

# 指定依列填入
A <- matrix(1:9, nrow=3, byrow=TRUE)

結果

     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

2 矩陣維度

dim(A)

結果

3 3

取得

nrow(A)
ncol(A)

3 取矩陣元素

A[1,2]     # 第1列第2行
A[1,]      # 第1列
A[,2]      # 第2行

4 矩陣轉置

t(A)

5 矩陣乘法

元素乘法

A * B

矩陣乘法

A %*% B

6 單位矩陣

diag(3)

結果

     [,1] [,2] [,3]
[1,] 1    0    0
[2,] 0    1    0
[3,] 0    0    1

7 取對角線

diag(A)

8 矩陣反矩陣

solve(A)

9 解線性方程組

Ax = b

A <- matrix(c(2,1,1,3),2,2)
b <- c(1,2)

x <- solve(A,b)

10 行列式

det(A)

11 eigen decomposition

eigen(A)

12 SVD

svd(A)

回傳

U
D
V

13 row 與 column 計算

column sum

colSums(A)

row sum

rowSums(A)

column mean

colMeans(A)

row mean

rowMeans(A)

14 apply 做矩陣運算

row

apply(A,1,sum)

column

apply(A,2,sum)

15 外積

outer(x,y)

範例

x <- 1:3
y <- 1:3

outer(x,y)

結果

     [,1] [,2] [,3]
[1,] 1    2    3
[2,] 2    4    6
[3,] 3    6    9

16 向量內積

sum(x*y)

t(x) %*% y

17 向量長度(norm)

L2 norm

sqrt(sum(x^2))

norm(as.matrix(x),"2")

18 建立零矩陣

matrix(0,n,m)

19 建立常數矩陣

matrix(5,n,m)

20 向量化計算(演算法很重要)

R 的核心優勢

x <- 1:1000000

sum(x^2)

for(i in 1:length(x)){
}

快很多


21 logical indexing(演算法常用)

x <- c(1,5,10,20)

x[x > 5]

結果

10 20

22 which(找 index)

which(x > 5)

結果

3 4

23 矩陣展平

as.vector(A)

24 reshape matrix

dim(x) <- c(3,3)

25 Kronecker product

kronecker(A,B)

26 cross product

crossprod(A,B)

等於

t(A) %*% B

27 tcrossprod

tcrossprod(A,B)

等於

A %*% t(B)

28 trace(矩陣跡)

R 沒有內建

自己寫

sum(diag(A))

29 cumulative sum

cumsum(x)

30 cumulative product

cumprod(x)

31 差分(時間序列常用)

diff(x)

32 normalize

x / sum(x)

如果你是做「演算法 / 最佳化 / ML」

這 10 個最常用

matrix()
t()
%*%
solve()
diag()
colSums()
rowSums()
apply()
crossprod()
svd()

幾乎涵蓋

  • Gradient descent
  • Linear regression
  • PCA
  • Optimization
  • Numerical methods

R Base for Algorithms / Numerical Computing Cheat Sheet

1 向量 (Vector)

建立向量

x <- c(1,2,3)
x <- 1:10
x <- seq(0,1,by=0.1)
x <- rep(1,5)

向量長度

length(x)

向量運算

x + y
x - y
x * y
x / y
x ^ 2

向量篩選

x[x > 5]

找 index

which(x > 5)

2 矩陣 (Matrix)


建立矩陣

A <- matrix(1:9,nrow=3)
A <- matrix(1:9,nrow=3,byrow=TRUE)

查看矩陣大小

dim(A)
nrow(A)
ncol(A)

取元素

A[1,2]
A[1,]
A[,2]

3 矩陣基本運算


矩陣加減

A + B
A - B

元素乘法

A * B

矩陣乘法

A %*% B

轉置

t(A)

4 矩陣重要運算


單位矩陣

diag(3)

對角線

diag(A)

trace

sum(diag(A))

determinant

det(A)

inverse matrix

solve(A)

解線性方程

Ax=b

solve(A,b)

5 行列運算


column sum

colSums(A)

row sum

rowSums(A)

column mean

colMeans(A)

row mean

rowMeans(A)

6 apply family


apply

矩陣運算

apply(A,1,sum)
1 = row
2 = column

sapply

sapply(x,sqrt)

lapply

lapply(list(1:3,4:6),sum)

tapply

tapply(x,group,mean)

7 向量內積與外積


inner product

sum(x*y)

t(x) %*% y

outer product

outer(x,y)

8 高階矩陣運算


eigen decomposition

eigen(A)

回傳

values
vectors

SVD

svd(A)

回傳

u
d
v

cross product

crossprod(A,B)

等於

t(A) %*% B

tcrossprod

tcrossprod(A,B)

等於

A %*% t(B)

Kronecker product

kronecker(A,B)

9 向量數值運算


L2 norm

sqrt(sum(x^2))

normalize

x/sum(x)

cumulative sum

cumsum(x)

cumulative product

cumprod(x)

difference

diff(x)

10 隨機數(來自機率分配)


uniform

runif(n)

normal

rnorm(n)

binomial

rbinom(n,size,p)

11 統計分布函數

R 有固定命名規則

函數 功能
r random
d density
p cdf
q quantile

normal distribution

rnorm()
dnorm()
pnorm()
qnorm()

binomial

rbinom()
dbinom()
pbinom()
qbinom()

poisson

rpois()
dpois()
ppois()
qpois()

12 排序


sort(x)

reverse sort

sort(x,decreasing=TRUE)

order index

order(x)

13 抽樣


sample(1:10,5)

sample(1:10,5,replace=TRUE)

14 重要工具函數


unique

unique(x)

table

table(x)

NA 處理

is.na(x)
na.omit(x)

15 數值演算法常用技巧


建立零矩陣

matrix(0,n,m)

常數矩陣

matrix(5,n,m)

reshape

dim(x) <- c(3,3)

matrix flatten

as.vector(A)

16 演算法效率技巧(非常重要)


向量化 > for loop

for(i in 1:n){
}

sum(x^2)

matrix operation > loop

for

%*%
crossprod
colSums

17 演算法最常用 15 個函數

如果你做

  • Machine Learning
  • Optimization
  • Numerical Methods
  • Statistics

最常用

matrix()
t()
%*%
solve()
diag()
det()
colSums()
rowSums()
apply()
outer()
crossprod()
svd()
eigen()
norm()
sample()

18 常見演算法應用

Linear Regression

solve(t(X)%*%X) %*% t(X) %*% y

PCA

eigen(cov(X))

Gradient descent

t(X) %*% (X %*% w - y)

演算法 50 個必備技巧(Base R)

1 建立零向量 / 零矩陣

演算法初始化很常用

x <- numeric(n)
A <- matrix(0,n,m)

2 建立常數矩陣

matrix(5,n,m)

3 初始化隨機參數

ML / optimization

w <- rnorm(d)

4 向量內積

sum(x*y)

t(x) %*% y

5 向量 L2 norm

sqrt(sum(x^2))

6 向量 L1 norm

sum(abs(x))

7 normalize vector

x / sqrt(sum(x^2))

8 matrix transpose

t(A)

9 matrix multiplication

A %*% B

10 element-wise multiplication

A * B

11 matrix inverse

solve(A)

12 解線性方程

Ax=b

solve(A,b)

13 determinant

det(A)

14 trace

sum(diag(A))

15 identity matrix

diag(n)

16 column sum

colSums(A)

17 row sum

rowSums(A)

18 column mean

colMeans(A)

19 row mean

rowMeans(A)

20 outer product

outer(x,y)

21 cross product(快速矩陣乘)

crossprod(A,B)

等於

t(A)%*%B

但更快


22 tcrossprod

tcrossprod(A,B)

等於

A%*%t(B)

23 eigen decomposition

eigen(A)

24 singular value decomposition

svd(A)

25 QR decomposition

線性回歸常用

qr(A)

26 Cholesky decomposition

正定矩陣

chol(A)

27 covariance matrix

cov(X)

28 correlation matrix

cor(X)

29 cumulative sum

cumsum(x)

30 cumulative product

cumprod(x)

31 difference

diff(x)

32 logical indexing

x[x>5]

33 找 index

which(x>5)

34 sorting

sort(x)

35 sorting index

order(x)

36 sample

Monte Carlo 很常用

sample(1:n,k)

37 隨機常態

rnorm(n)

38 隨機 uniform

runif(n)

39 Monte Carlo integration

mean(f(runif(n)))

40 apply matrix operation

row

apply(A,1,sum)

column

apply(A,2,sum)

41 向量化計算

sum(x^2)

for(i in 1:n){
}

42 reshape vector → matrix

dim(x) <- c(n,m)

43 flatten matrix

as.vector(A)

44 NA handling

is.na(x)

45 remove NA

na.omit(x)

46 unique

unique(x)

47 frequency table

table(x)

48 梯度數值近似

finite difference

grad <- function(f,x,h=1e-6){
  (f(x+h)-f(x-h))/(2*h)
}

49 梯度下降

for(i in 1:1000){
  w <- w - lr * grad
}

50 線性回歸 closed form

beta <- solve(t(X)%*%X) %*% t(X) %*% y

R 寫演算法最重要的 10 個函數

如果你做

  • ML
  • Optimization
  • Statistics
  • Numerical methods

幾乎每天會用

matrix()
t()
%*%
solve()
diag()
colSums()
rowSums()
crossprod()
svd()
eigen()

最重要的 R 演算法技巧

  1. 向量化:永遠比 loop 快

2.用 matrix operation:不要自己寫 double loop

  1. crossprod 比 %*% 更快

  2. solve(A,b) 比 solve(A)%*%b 快


R Optimization / ML 數值技巧 Cheat Sheet

1 Gradient Descent(向量化版本)

避免 loop

grad <- function(X,y,w){

  t(X) %*% (X %*% w - y)

}

for(i in 1:1000){

  w <- w - lr * grad(X,y,w)

}

2 Logistic Regression gradient

sigmoid <- function(z){
  1/(1+exp(-z))
}

grad <- function(X,y,w){

  p <- sigmoid(X %*% w)

  t(X) %*% (p-y)

}

3 softmax(數值穩定)

避免 overflow

softmax <- function(x){

  ex <- exp(x - max(x))

  ex / sum(ex)

}

4 log-sum-exp trick

常見於 ML likelihood

logsumexp <- function(x){

  m <- max(x)

  m + log(sum(exp(x-m)))

}

5 cross entropy

loss <- function(y,p){

  -sum(y*log(p))

}

6 vectorized loss

loss <- function(X,y,w){

  p <- sigmoid(X %*% w)

  -sum(y*log(p)+(1-y)*log(1-p))

}

7 Numerical gradient

finite difference

num_grad <- function(f,x,h=1e-6){

  (f(x+h)-f(x-h))/(2*h)

}

8 Gradient checking

檢查 analytic gradient

abs(num_grad(f,x)-grad(x))

9 Projection / normalization

x / sqrt(sum(x^2))

10 clipping(防 overflow)

p <- pmax(pmin(p,1-1e-10),1e-10)

11 covariance 快速計算

cov(X)

t(scale(X,scale=FALSE)) %*% scale(X,scale=FALSE) / (n-1)

12 PCA

eig <- eigen(cov(X))

eig$vectors
eig$values

13 Fast linear regression

closed form

beta <- solve(t(X)%*%X, t(X)%*%y)

solve(t(X)%*%X) %*% t(X)%*%y

更快


14 QR regression

更穩定

qr.solve(X,y)

15 Cholesky regression

X’X positive definite

R <- chol(t(X)%*%X)

beta <- backsolve(R,forwardsolve(t(R),t(X)%*%y))

16 Monte Carlo estimation

mean(f(runif(n)))

17 Monte Carlo integration example

f <- function(x){
  x^2
}

mean(f(runif(10000)))

18 importance sampling

mean(f(x)/g(x))

19 random initialization

w <- rnorm(d,0,0.01)

20 minibatch sampling

batch <- sample(1:n,batch_size)

21 shuffle dataset

idx <- sample(1:n)

X <- X[idx,]
y <- y[idx]

22 vectorized prediction

y_hat <- X %*% w

23 fast distance matrix

dist(X)

24 pairwise distance(手寫)

sqrt(outer(x,x,"-")^2)

25 k-means step

assign cluster

apply(dist_mat,1,which.min)

26 update centroid

colMeans(X[cluster==k,])

27 stochastic gradient descent

for(i in sample(1:n)){

  grad <- gradient(x[i,],y[i])

  w <- w - lr*grad

}

28 early stopping

if(abs(loss_old-loss_new)<1e-6){

  break

}

29 regularization (L2)

ridge

lambda*sum(w^2)

30 regularization gradient

grad <- grad + 2*lambda*w

R 寫 ML / Optimization 最重要 12 個函數

matrix()
t()
%*%
solve()
crossprod()
colSums()
rowMeans()
apply()
eigen()
svd()
sample()
rnorm()

最重要 5 個數值穩定技巧

  1. softmax 減 max
exp(x-max(x))
  1. log-sum-exp
m + log(sum(exp(x-m)))
  1. clipping probability
1e-10
  1. 避免 matrix inverse

solve(A,b)
  1. 向量化

避免

for loop

R Base Matrix / Linear Algebra Cheat Sheet

1 建立矩陣

A <- matrix(1:9, nrow=3)

指定 row 填入

A <- matrix(1:9, nrow=3, byrow=TRUE)

2 矩陣維度

dim(A)
nrow(A)
ncol(A)

3 取矩陣元素

A[1,2]
A[1,]
A[,2]

4 矩陣轉置

t(A)

5 矩陣加減

A + B
A - B

6 元素乘法

A * B

7 矩陣乘法

A %*% B

8 identity matrix

diag(n)

9 對角線

diag(A)

10 trace

sum(diag(A))

11 determinant

det(A)

12 inverse matrix

solve(A)

13 解線性方程

Ax=b

solve(A,b)

14 rank(矩陣秩)

qr(A)$rank

15 QR decomposition

qr(A)

取得 Q

qr.Q(qr(A))

取得 R

qr.R(qr(A))

16 Cholesky decomposition

正定矩陣

chol(A)

17 eigen decomposition

eig <- eigen(A)

eig$values
eig$vectors

18 singular value decomposition

svd(A)

回傳

u
d
v

19 pseudo inverse

Moore-Penrose

sv <- svd(A)

A_pinv <- sv$v %*% diag(1/sv$d) %*% t(sv$u)

20 condition number

kappa(A)

21 norm

矩陣 norm

norm(A,"2")

Frobenius norm

norm(A,"F")

22 vector norm

sqrt(sum(x^2))

23 column sum

colSums(A)

24 row sum

rowSums(A)

25 column mean

colMeans(A)

26 row mean

rowMeans(A)

27 outer product

outer(x,y)

28 inner product

sum(x*y)

t(x)%*%y

29 cross product

crossprod(A,B)

等於

t(A)%*%B

30 tcrossprod

tcrossprod(A,B)

等於

A%*%t(B)

31 Kronecker product

kronecker(A,B)

32 Gram matrix

t(X)%*%X

33 covariance matrix

cov(X)

34 correlation matrix

cor(X)

35 center matrix

scale(X,scale=FALSE)

36 normalize columns

scale(X)

37 projection matrix

P <- X %*% solve(t(X)%*%X) %*% t(X)

38 hat matrix(回歸)

H <- X %*% solve(t(X)%*%X) %*% t(X)

39 residual maker

M <- diag(n) - H

40 orthogonalization(Gram-Schmidt)

簡單版本

qr.Q(qr(A))

41 PCA

eig <- eigen(cov(X))

42 SVD PCA

svd(scale(X))

43 flatten matrix

as.vector(A)

44 reshape vector

dim(x) <- c(n,m)

45 block matrix

rbind(A,B)
cbind(A,B)

46 remove row

A[-i,]

47 remove column

A[,-j]

48 submatrix

A[1:3,1:3]

49 repeat matrix

rep(A,3)

50 zero matrix

matrix(0,n,m)

R 線性代數最常用 12 個指令

幾乎所有 ML / Statistics / Optimization

都會用

matrix()
t()
%*%
solve()
diag()
det()
eigen()
svd()
crossprod()
tcrossprod()
colMeans()
rowSums()

最重要 5 個數值技巧

  1. 不要直接 inverse

不要

solve(A)%*%b

solve(A,b)

  1. crossprod 更快

不要

t(X)%*%X

crossprod(X)
  1. tcrossprod
tcrossprod(X)
  1. QR 比 normal equation 穩定
qr.solve(X,y)
  1. SVD 最穩定
svd(X)
無符合的項目